package com.chinadrtv.batch.admin.jobs.ozing.gift;

import com.chinadrtv.batch.admin.jobs.ozing.common.OzingCardTransformer;
import com.chinadrtv.user.dao.ozing.OzingCardDao;
import com.chinadrtv.user.dao.ozing.OzingDao;
import com.chinadrtv.user.model.Device;
import com.chinadrtv.user.model.OzingCard;
import com.chinadrtv.user.model.User;
import com.chinadrtv.user.model.UserOzingBalance;
import com.chinadrtv.user.service.ozing.OzingService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * save card the {@link OzingCardProcessor} created.
 *
 * @author Jack Chen
 *         Date: 12-12-18
 */
public class OzingCardItemWriter implements ItemWriter<OzingCardTransformer> {
    private static Log log = LogFactory.getLog(OzingCardItemWriter.class);

    @Autowired
    private OzingDao userOzingCardDao;

    @Autowired
    private OzingCardDao ozingCardDao;

    public void setUserOzingCardDao(OzingDao userOzingCardDao) {
        this.userOzingCardDao = userOzingCardDao;
    }

    public void setOzingCardDao(OzingCardDao ozingCardDao) {
        this.ozingCardDao = ozingCardDao;
    }

    public void write(List<? extends OzingCardTransformer> items) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("*************OzingCardJob--Writer is running*************");
        }
        for (OzingCardTransformer ozingCardTransformer : items) {
                OzingCard ozingCard = ozingCardTransformer.getOzingCard();
                User user = ozingCardTransformer.getUser();
                Device device = ozingCardTransformer.getDevice();
                if (ozingCard != null) {
                    OzingCard o = ozingCardDao.save(ozingCard);
                    UserOzingBalance balance = userOzingCardDao.findOzingCardPointsByUsername(user.getUsername());
                    userOzingCardDao.redeemOzingCard(user.getUsername(), o, balance);
                    ozingCardDao.saveDeviceGiftCardHis(device, o);
                }
        }
    }
}
